#include <QtGui>
#include "tablesizewidget.h"

const int tableSizeWidget::size = 16;
const int tableSizeWidget::gap = 4;
const int tableSizeWidget::edgeGap = 24;

/**
  * Create the dialog and put it under the mouse cursor
  */
tableSizeWidget::tableSizeWidget(QWidget *parent) : QDialog(parent, Qt::FramelessWindowHint)
{
    //move the widget so the cursor is in the middle of the first box
    int offset = (size  / 2) + gap;
	move(QCursor::pos().x() - offset, QCursor::pos().y() - offset);

    numX = 3;   //the inital size of the grid
    numY = 3;

    setMouseTracking(true);
    update();
}

/**
  * Draw the widget based on the number of boxes
  */
void tableSizeWidget::paintEvent(QPaintEvent *event)
{
    //calculate size of window
	int sizeX = ((size + gap) * numX) + edgeGap;
	int sizeY = ((size + gap) * numY) + edgeGap;
	resize(sizeX, sizeY);

    QPainter painter(this);

    //draw the grid
	for (int x = gap; x < sizeX - edgeGap; x += (size + gap))
    {
		for (int y = gap; y < sizeY - edgeGap; y += (size + gap))
	{
			painter.fillRect(x, y, size, size, Qt::darkGray);
			painter.drawRect(x, y, size, size);
	}
    }

	//print the numbers of cells
	QString text = QString::number(numX) + "x" + QString::number(numY);
	painter.drawText(QPoint(gap, sizeY - gap), text);

	event->accept();
}

/**
  * Closes the widget if the user moves their mouse of the top/left side
  */
void tableSizeWidget::leaveEvent(QEvent *event)
{
	checkMouse();

	event->accept();
}

/**
  * Updates (and possibly expands) the grid when the mouse is moved
  */
void tableSizeWidget::mouseMoveEvent(QMouseEvent *event)
{
	checkMouse();

	event->accept();
}

/**
  * Checks the mouse's position and reacts accordingly
  */
void tableSizeWidget::checkMouse()
{
	QPoint pos = mapFromGlobal(cursor().pos());

	//if the mouse leaves the dialog to the left/top
	if (pos.x() < 0 || pos.y() < 0)
		reject();

	//expand to add new cells
	if (pos.x() > (width() - edgeGap))
		numX++;

	if (pos.y() > (height() - edgeGap))
		numY++;

	//contract to remove cells
	if (pos.x() < (width() - size - edgeGap - gap))
		numX--;

	if (pos.y() < (height() - size  - edgeGap - gap))
		numY--;

	update();   //call the paint function to update everything
}

/**
  * Confirm a selection
  */
void tableSizeWidget::mouseReleaseEvent(QMouseEvent *event)
{
    accept();

    event->accept();
}
